const app = getApp();
import dayjs from "../../../../utils/dayjs";
const kugou = require('../../../../utils/kugouMusic');
const backgroundAudioManager = wx.getBackgroundAudioManager();
// packageMore/pages/music/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hide: app.globalData.hide,
    section: 0,
    flag: false,
    isPlay: false,
    myInterval: null,
    newMusicList: [],
    rankMusicList: [],
    plistMusicList: [],
    singerList: [],
    currentMusicInfo: {},
    bannerList: [],
    currentHash: ''
  },

  devGoHome() {
    wx.switchTab({
      url: "/pages/index/index",
    });
    wx.showTabBar();
  },

  handleTab(e) {
    const { id } = e.currentTarget.dataset;
    this.setData({
      section: id
    });
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },

  getNewMusic() {
    const that = this;
    kugou.getNewMusic().then(res => {
      that.setData({
        newMusicList: res.data.data,
        bannerList: res.data.banner
      })
    }).catch(err => {
      wx.showToast({
        title: err.errMsg,
        icon: 'none'
      })
    })
  },

  getRankMusic() {
    const that = this;
    kugou.getRankMusic().then(res => {

      // console.log(res.data.rank.list);
      that.setData({
        rankMusicList: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.errMsg,
        icon: 'none'
      })
    })
  },

  getPlistMusic() {
    const that = this;
    kugou.getPlistMusic().then(res => {
      that.setData({
        plistMusicList: res
      })
    }).catch(err => {
      wx.showToast({
        title: err.errMsg,
        icon: 'none'
      })
    })
  },

  getSingerClass() {
    const that = this;
    kugou.getSingerClass().then(res => {
      // console.log(res.data.list);
      that.setData({
        singerList: res.data.list
      })
    }).catch(err => {
      wx.showToast({
        title: err.errMsg,
        icon: 'none'
      })
    })
  },

  goToSongList(e) {
    const { id, type } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageMore/pages/music/songList/songList?id=' + id + "&type=" + type,
    })
  },

  goToSingerList(e) {
    const { id, type } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageMore/pages/music/singer/singer?id=' + id + "&type=" + type,
    })
  },

  goSearch() {
    wx.navigateTo({
      url: '/packageMore/pages/music/search/search',
    })
  },

  playMusic(e) {
    const that = this;
    const { newMusicList, currentHash, isPlay } = that.data;
    const { hash } = e.currentTarget.dataset;
    if (isPlay && currentHash == hash) {
      app.handleMusic(true, () => {
        that.setData({ isPlay: false });
      });
      return;
    }
    if (!isPlay && currentHash == hash) {
      app.handleMusic(false, () => {
        that.setData({ isPlay: true });
      });
      return;
    }
    kugou.infoMusic(hash).then(result => {
      console.log(result.data);
      let { error, singerName, songName, album_img, url } = result.data;
      album_img = album_img.replace('{size}/', '');
      if (error != '') {
        wx.showToast({
          title: error,
          icon: 'none'
        })
      } else {
        that.setData({
          currentHash: hash,
          isPlay: true
        });
        app.globalData.isPlay = true;
        app.globalData.currentHash = hash;

        app.setMisic(
          { singerName, songName, album_img, url },
          () => {
            app.globalData.isPlay = false;
            app.globalData.currentHash = '';
            that.setData({ currentHash: '', isPlay: false });
          },
          () => {
            app.globalData.isPlay = true;
            that.setData({ isPlay: true });
          },
          () => {
            app.globalData.isPlay = false;
            that.setData({ isPlay: false });
          }
        );
        // that.setMisic({ singerName, songName, imgUrl, url });
        // wx.setStorageSync('current_music_list', newMusicList);
        that.setData({
          currentMusicInfo: { singerName, songName, imgUrl, url },
          isPlay: true,
          currentHash: hash
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.errMsg,
        icon: 'none'
      })
    })
  },

  setMisic(current) {
    const that = this;
    let { myInterval } = that.data;
    clearInterval(myInterval);
    backgroundAudioManager.startTime = 0;
    backgroundAudioManager.currentTime = 0;
    backgroundAudioManager.title = current.songName;
    backgroundAudioManager.src = current.url;
    backgroundAudioManager.singer = current.singerName;
    backgroundAudioManager.coverImgUrl = current.imgUrl;

    // this.playMusicError();

    myInterval = setInterval(() => {
      //判断滑块是否在推动
      if (that.data.flag === false) {
        let a =
          dayjs(backgroundAudioManager.duration * 1000).format("mm:ss") ||
          "00:00"; //总时长 用dayjs对总时长进行处理
        let b = parseInt(backgroundAudioManager.duration); //滑块最大值
        let c =
          dayjs(backgroundAudioManager.currentTime * 1000).format("mm:ss") ||
          "00:00"; //当前时长
        let d = parseInt(backgroundAudioManager.currentTime); //滑块值
        // this.setData({
        //   totalTime: a, ///总时长 对数据进行处理后
        //   max: b, //滑块最大数
        //   currentTime: c,
        //   value: d,
        // });

        app.globalData.totalTime = a;
        app.globalData.max = b;
        app.globalData.currentTime = c;
        app.globalData.value = d;
        app.globalData.isPlay = true;

        // console.log("定时器", this.data.currentTime);
        backgroundAudioManager.onEnded(() => {
          clearInterval(myInterval);
          that.setData({ isPlay: false, currentHash: '' });
        });
      }
    }, 1000);
    that.setData({
      myInterval
    })
    // this.nextMusicAutoPlay();

  },

  goPlayPage() {
    let { currentMusicInfo } = this.data;
    currentMusicInfo = JSON.stringify(currentMusicInfo);
    wx.navigateTo({
      url: '/packageMore/pages/music/play/play?current=' + currentMusicInfo,
    })
  },

  handlePlay() {
    let { isPlay, myInterval } = this.data;
    switch (isPlay) {
      case true:
        backgroundAudioManager.pause();
        backgroundAudioManager.onPause(() => {
          app.globalData.isPlay = false;
          // clearInterval(myInterval);
          this.setData({
            isPlay: false,
          });
        });
        break;
      case false:
        backgroundAudioManager.play();
        backgroundAudioManager.onPlay(() => {
          app.globalData.isPlay = true;
          this.setData({
            isPlay: true,
          });
        });
        break;

      default:
        break;
    }
  },

  showMusicList() { },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getNewMusic();
    this.getRankMusic();
    this.getPlistMusic();
    this.getSingerClass();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      currentHash: app.globalData.currentHash || "",
      isPlay: app.globalData.isPlay || false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getNewMusic();
    this.getRankMusic();
    this.getPlistMusic();
    this.getSingerClass();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})